package weatherwidget.isrefluxer.bird.com.birdweatherwidget.service;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Base64;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import weatherwidget.isrefluxer.bird.com.birdweatherwidget.constant.WeatherConstant;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.data.DatabaseHelper;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.data.WeatherInfo;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.until.LogUtil;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.until.WeatherUtil;

/**
 * Created by Administrator on 2016/11/22.
 */

public class WeathersManager {

    private static final String TAG = "WeatherManager";


    public static void updateAll(final Context context) {

        String[] citys = DatabaseHelper.getCitys(context);
        String requsetUrl;
        FinalHttp fh = new FinalHttp();
        if(citys!=null&&citys.length>0){
            DatabaseHelper.deleteOldWeathers(context);
            for (final String city:citys) {
                LogUtil.log(TAG,"city: "+city);
                requsetUrl = getRequestUri(city);
                LogUtil.log(TAG,
                        "requsetUrl:" + requsetUrl);
               fh.get(requsetUrl, new AjaxCallBack<String>() {
                   @Override
                   public void onSuccess(String s) {
                       ArrayList<WeatherInfo> weaherInfos = null;
                       try {
                           weaherInfos = WeatherUtil.parseWeaherInfo(s);
                           if (weaherInfos == null || weaherInfos.size() == 0) {
                               LogUtil.log(TAG,"weaherInfos.size()==0");
                               context.sendBroadcast(new Intent(
                                       WeatherConstant.ACTION_WEATHER_UPDATE_FAILURE));
                           }
                           else {
                               LogUtil.log(TAG,"weaherInfos.size()>0");
                                DatabaseHelper.writeWeather(context,
                                        weaherInfos);
                               Intent intent = new Intent(WeatherConstant.ACTION_WEATHER_UPDATE_SUCCESS);
                               intent.putExtra("city",city);
                               context.sendBroadcast(intent);
                               LogUtil.log(TAG,"sendBroadcast(ACTION_WEATHER_UPDATE_SUCCESS)");

                           }
                           LogUtil.log("test", "FinalHttp onSuccess:" + s);
                       }catch (JSONException e){
                           context.sendBroadcast(new Intent(
                                   WeatherConstant.ACTION_WEATHER_UPDATE_FAILURE));

                       }
                   }

                   @Override
                   public void onFailure(Throwable t, int errorNo, String strMsg) {
                       context.sendBroadcast(new Intent(
                               WeatherConstant.ACTION_WEATHER_UPDATE_FAILURE));
                       LogUtil.log(TAG, "FinalHttp onFailure=" + strMsg
                               + " errorNo=" + errorNo);
                   }
               });

            }
        }
    }

    private static String getRequestUri(String city) {
        LogUtil.log(TAG,"city: "+city);
//        String encodeCity = null;
//        try {
//             encodeCity = new String(Base64.encode(URLEncoder.encode(city,"UTF-8").getBytes(),Base64.NO_WRAP));
//
//        } catch (UnsupportedEncodingException e) {
//        }
        return WeatherConstant.WEATHER_SER_URL +city;
    }

    public static void updateCity(final Context context, final String city,
                                  final String isLocal) {
        if(TextUtils.isEmpty(city)){
            return;
        }
        FinalHttp fh = new FinalHttp();
        String requsetUrl = getRequestUri(city);
        LogUtil.log(TAG, "requsetUrl=" + requsetUrl);
        fh.get(requsetUrl, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                LogUtil.log(TAG, "FinalHttp onSuccess=" + s);
                try {
                    ArrayList<WeatherInfo> weaherInfos = WeatherUtil
                            .parseWeaherInfo(s);
                    Intent i;
                    if (weaherInfos == null || weaherInfos.size() == 0) {
                        i = new Intent(
                                WeatherConstant.ACTION_WEATHER_UPDATE_NULL);
                        i.putExtra("city", city);
                        context.sendBroadcast(i);
                    }else {
                        LogUtil.log(TAG,"weaherInfos.size()>0");
                        DatabaseHelper.writeWeather(context, weaherInfos);
                        DatabaseHelper.insertCity(context, city, weaherInfos
                                        .get(0).getValueByKey(WeatherInfo.CITY_ID),
                                isLocal);
                        i = new Intent(
                                WeatherConstant.ACTION_WEATHER_UPDATE_SUCCESS);
                        i.putExtra("city", city);
                        context.sendBroadcast(i);

                    }

                }catch (Exception e) {
                    context.sendBroadcast(new Intent(
                            WeatherConstant.ACTION_WEATHER_UPDATE_FAILURE));
                }

                //super.onSuccess(s);
            }
        });

    }
}
